package com.shz.appletsapi.controller;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import javax.mail.MessagingException;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.shz.appletsapi.common.ControllerDataResult;
import com.shz.appletsapi.common.ControllerResult;
import com.shz.appletsapi.exception.ShzException;
import com.shz.appletsapi.model.po.LahuoMonitor;
import com.shz.appletsapi.repository.LahuoMonitorRepository;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("/home")
public class HomeController {

	@Autowired
	private LahuoMonitorRepository lahuoMonitorRepository;

	@Autowired
	private AmqpTemplate amqpTemplate;

	@RequestMapping("/")
	public Object index() throws MessagingException {
		return "hello";
	}

	@PostMapping("/saveMonitorLog")
	public ControllerResult saveMonitorLog(@RequestParam("appId") String appId, @RequestParam("content") String content)
			throws Exception {

		LahuoMonitor lahuoMonitor = new LahuoMonitor();
		lahuoMonitor.setAppId(appId);
		lahuoMonitor.setContent(content);
		// 对象转化为字节码 把对象转化为字节码后，把字节码传输过去再转化为对象
		byte[] bytes = getBytesFromObject(lahuoMonitor);

		try {
			amqpTemplate.convertAndSend("lahuo.monitor", bytes);
		} catch (Exception e) {
			throw new ShzException(e.getMessage());
		}

		return new ControllerResult();
	}

	// 对象转化为字节码
	public byte[] getBytesFromObject(Serializable obj) throws Exception {
		if (obj == null) {
			return null;
		}
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		ObjectOutputStream oo = new ObjectOutputStream(bo);
		oo.writeObject(obj);
		return bo.toByteArray();
	}

}
